package com.ruoyi.web.controller.ora;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.dict.*;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ora.constant.BizConstants;
import com.ruoyi.ora.domain.*;
import com.ruoyi.ora.factory.AiFactory;
import com.ruoyi.ora.service.*;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 录音回忆录Controller
 * 
 * @author liuwp
 * @date 2025-04-10
 */
@RestController
@RequestMapping("/ora/voice_memoir")
public class VoiceMemoirController extends BaseController
{
    @Autowired
    private IVoiceStoryService voiceStoryService;
    @Autowired
    private IDeviceUserService deviceUserService;
    @Autowired
    private IVoiceRecordService voiceRecordService;
    @Autowired
    private IVoiceMemoirService voiceMemoirService;

    @Autowired
    private IAssetsPermissionService assetsPermissionService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IAssetsRecycleService assetsRecycleService;

    /**
     * 查询录音回忆录列表
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:list')")
    @GetMapping("/list")
    public TableDataInfo list(VoiceMemoir voiceMemoir)
    {
        startPage();
        List<VoiceMemoir> list = voiceMemoirService.selectVoiceMemoirList(voiceMemoir);
        return getDataTable(list);
    }

    /**
     * 导出录音回忆录列表
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:export')")
    @Log(title = "录音回忆录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VoiceMemoir voiceMemoir)
    {
        List<VoiceMemoir> list = voiceMemoirService.selectVoiceMemoirList(voiceMemoir);
        ExcelUtil<VoiceMemoir> util = new ExcelUtil<VoiceMemoir>(VoiceMemoir.class);
        util.exportExcel(response, list, "录音回忆录数据");
    }

    /**
     * 获取录音回忆录详细信息
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        VoiceMemoir voiceMemoir = voiceMemoirService.selectVoiceMemoirById(id);
        if (voiceMemoir == null){
            if (StringUtils.isNotEmpty(voiceMemoir.getVoiceIds())){
                String[] ids = voiceMemoir.getVoiceIds().split(",");
                List<VoiceRecord> voiceRecords = new ArrayList<VoiceRecord>();
                for (String idStr : ids){
                    VoiceRecord voiceRecord = voiceRecordService.selectVoiceRecordById(Long.valueOf(idStr));
                    if (voiceRecord != null){
                        voiceRecords.add(voiceRecord);
                    }
                }
                voiceMemoir.setVoiceRecords(voiceRecords);
            }
            if (StringUtils.isNotEmpty(voiceMemoir.getMemoirIds())){
                String[] ids = voiceMemoir.getMemoirIds().split(",");
                List<VoiceMemoir> voiceMemoirs = new ArrayList<VoiceMemoir>();
                for (String idStr : ids){
                    VoiceMemoir voiceMemoir1 = voiceMemoirService.selectVoiceMemoirById(Long.valueOf(idStr));
                    if (voiceMemoir1 != null){
                        voiceMemoirs.add(voiceMemoir1);
                    }
                }
                voiceMemoir.setVoiceMemoirs(voiceMemoirs);
            }
            if (StringUtils.isNotEmpty(voiceMemoir.getStoryIds())){
                String[] ids = voiceMemoir.getStoryIds().split(",");
                List<VoiceStory> voiceStorys = new ArrayList<VoiceStory>();
                for (String idStr : ids){
                    VoiceStory voiceStory1 = voiceStoryService.selectVoiceStoryById(Long.valueOf(idStr));
                    if (voiceStory1 != null){
                        voiceStorys.add(voiceStory1);
                    }
                }
                voiceMemoir.setVoiceStorys(voiceStorys);
            }
        }
        return AjaxResult.success(voiceMemoir);
    }

    /**
     * 新增录音回忆录
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:add')")
    @Log(title = "录音回忆录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VoiceMemoir voiceMemoir)
    {
        return toAjax(voiceMemoirService.insertVoiceMemoir(voiceMemoir));
    }

    /**
     * 修改录音回忆录
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:edit')")
    @Log(title = "录音回忆录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VoiceMemoir voiceMemoir)
    {
        return toAjax(voiceMemoirService.updateVoiceMemoir(voiceMemoir));
    }

    /**
     * 删除录音回忆录
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:remove')")
    @Log(title = "录音回忆录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int delCount = 0;
        for (Long id : ids) {
            int result = voiceMemoirService.updateVoiceMemoir(Builder.of(VoiceMemoir::new).with(VoiceMemoir::setId, id).with(VoiceMemoir::setDeleteTime, new Date()).build());
            delCount += result;
            if (result > 0) {
                // 添加到回收站
                assetsRecycleService.insertAssetsRecycle(Builder.of(AssetsRecycle::new)
                        .with(AssetsRecycle::setAssetsType, AssetsType.MEMORI.getValue())
                        .with(AssetsRecycle::setAssetsId, id)
                        .with(AssetsRecycle::setUserId, SecurityUtils.getUserId())
                        .build());
            }
        }
        return toAjax(delCount);
//        return toAjax(voiceMemoirService.deleteVoiceMemoirByIds(ids));
    }

    /*****************************************/


    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:list')")
    @GetMapping("/query")
    public TableDataInfo query(VoiceMemoir voiceMemoir)
    {
        if (voiceMemoir.getDeviceId() == null){
            return getDataTable(new ArrayList<VoiceMemoir>());
        }else {
            List<VoiceMemoir> list = null; // voiceMemoirService.selectVoiceMemoirList(voiceMemoir);

            if (voiceMemoir.getShowType() != null && voiceMemoir.getShowType().intValue() == AssetsShowType.COLLECTION.getValue().intValue()){
                voiceMemoir.setUserId(SecurityUtils.getUserId());
                startPage();
                list = voiceMemoirService.selectVoiceMemoirListCollection(voiceMemoir);
            }else {
                boolean isAdmin = false;

                // 要先判断自己的权限
                if (voiceMemoir.getDeviceId() != null){
                    DeviceUser deviceUser = deviceUserService.selectOneDeviceUser(Builder.of(DeviceUser::new)
                            .with(DeviceUser::setUserId, SecurityUtils.getUserId())
                            .with(DeviceUser::setDeviceId, voiceMemoir.getDeviceId())
                            .build());

                    if (deviceUser == null){
                        return getDataTable(new ArrayList<VoiceRecord>());
                    }
                    voiceMemoir.setDeviceUserId(deviceUser.getId());
                    if (deviceUser.getDevicePermission().intValue() == DevicePermission.ADMIN.getValue().intValue()){
                        isAdmin = true;
                    }
                }

                if (!isAdmin && voiceMemoir.getShowType() != null && voiceMemoir.getShowType().intValue() == AssetsShowType.PARTABLE.getValue().intValue()){
                    startPage();
                    list = voiceMemoirService.selectVoiceMemoirListDeviceUser(voiceMemoir);
                }else {
                    startPage();
                    list = voiceMemoirService.selectVoiceMemoirList(voiceMemoir);
                }
            }

            List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
            Map<Long, SysUser> userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, user -> user));

            for (VoiceMemoir memoir : list) {
                memoir.setSysUser(userMap.get(memoir.getUserId()));
            }
            return getDataTable(list);

        }
    }

    @PostMapping("/preview")
    public AjaxResult preview(VoiceMemoir voiceMemoir)
    {
        String contentAll = "";  // 选择的所有记录和故事
        //生成回忆录
        if (StringUtils.isNotEmpty(voiceMemoir.getVoiceIds())){
            String[] voiceIds = voiceMemoir.getVoiceIds().split(",");
            for (String voiceId : voiceIds) {

                VoiceRecord voiceRecord = voiceRecordService.selectVoiceRecordById(Long.valueOf(voiceId));
                if (voiceRecord != null && StringUtils.isNotEmpty(voiceRecord.getVoiceContent())){
                    contentAll = contentAll + voiceRecord.getVoiceContent() + "。";
                }
            }
        }

        if (StringUtils.isNotEmpty(voiceMemoir.getStoryIds())){
            String[] storyIds = voiceMemoir.getStoryIds().split(",");
            for (String storyId : storyIds) {
                VoiceStory voiceStory = voiceStoryService.selectVoiceStoryById(Long.valueOf(storyId));
                if (voiceStory != null && StringUtils.isNotEmpty(voiceStory.getContent())){
                    contentAll = contentAll + voiceStory.getContent() + "。";
                }
            }
        }

        if (StringUtils.isNotEmpty(contentAll)){
            String content = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(contentAll+"。请根据以上内容写一篇"+VoiceMemoirArticleLength.getLabelByValue(voiceMemoir.getArticleLength().intValue())+"的"+VoiceMemoirWriteType.getLabelByValue(voiceMemoir.getWriteType().intValue()));
            String memoirContent = content.contains("error")?"":content;
            voiceMemoir.setContent(memoirContent);

            String title = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceMemoir.getContent()+"。请给以上内容做一个10字左右的总结");
            String memoirTitle = title.contains("error")?voiceMemoir.getContent().length()>10?voiceMemoir.getContent().substring(0, 10):voiceMemoir.getContent():title;
            voiceMemoir.setTitle(memoirTitle);
        }

        return AjaxResult.success(voiceMemoir);
    }

    @PreAuthorize("@ss.hasPermi('ora:voice_memoir:add')")
    @Log(title = "录音回忆录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addMemoir(VoiceMemoir voiceMemoir, MultipartFile coverFile)
    {
        voiceMemoir.setUserId(SecurityUtils.getUserId());

        if (coverFile != null){
            try {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, coverFile);
                AjaxResult ajax = AjaxResult.success();
                ajax.put("fileName", fileName);
                voiceMemoir.setCover(fileName);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

//        String contentAll = "";  // 选择的所有记录和故事
//        //生成回忆录
//        if (StringUtils.isNotEmpty(voiceMemoir.getVoiceIds())){
//            String[] voiceIds = voiceMemoir.getVoiceIds().split(",");
//            for (String voiceId : voiceIds) {
//
//                VoiceRecord voiceRecord = voiceRecordService.selectVoiceRecordById(Long.valueOf(voiceId));
//                if (voiceRecord != null && StringUtils.isNotEmpty(voiceRecord.getVoiceContent())){
//                    contentAll = contentAll + voiceRecord.getVoiceContent() + "。";
//                }
//            }
//        }
//
//        if (StringUtils.isNotEmpty(voiceMemoir.getStoryIds())){
//            String[] storyIds = voiceMemoir.getStoryIds().split(",");
//            for (String storyId : storyIds) {
//                VoiceStory voiceStory = voiceStoryService.selectVoiceStoryById(Long.valueOf(storyId));
//                if (voiceStory != null && StringUtils.isNotEmpty(voiceStory.getContent())){
//                    contentAll = contentAll + voiceStory.getContent() + "。";
//                }
//            }
//        }

//        if (StringUtils.isNotEmpty(contentAll)){
//            String content = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(contentAll+"。请根据以上内容写一篇"+VoiceMemoirArticleLength.getLabelByValue(voiceMemoir.getArticleLength().intValue())+"的"+VoiceMemoirWriteType.getLabelByValue(voiceMemoir.getWriteType().intValue()));
//            String memoirContent = content.contains("error")?"":content;
//            voiceMemoir.setContent(memoirContent);
//
//            String title = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceMemoir.getContent()+"。请给以上内容做一个10字左右的总结");
//            String memoirTitle = title.contains("error")?voiceMemoir.getContent().length()>10?voiceMemoir.getContent().substring(0, 10):voiceMemoir.getContent():title;
//            voiceMemoir.setTitle(memoirTitle);
//        }

        int result = voiceMemoirService.insertVoiceMemoir(voiceMemoir);

        if (voiceMemoir.getShowType() == null) voiceMemoir.setShowType(AssetsShowType.ADMINABLE.getValue());
        assetsPermissionService.assetsPermissionGrant(Builder.of(AssetsPermission::new)
                .with(AssetsPermission::setAssetsId, voiceMemoir.getId())
                .with(AssetsPermission::setDeviceUserIds, voiceMemoir.getDeviceUserIds())
                .with(AssetsPermission::setShowType, voiceMemoir.getShowType())
                .with(AssetsPermission::setAssetsType, AssetsType.MEMORI.getValue())
                .build());
        return toAjax(result);
    }
}
